package com.example.musicdemo.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;


import com.example.musicdemo.views.MainActivity;
import com.example.musicdemo.R;
import com.example.musicdemo.listener.OnMusicPlayStateChangeListener;
import com.example.musicdemo.receiver.NotificationReceiver;
import com.example.musicdemo.utils.Utils;

import java.io.IOException;

public class MusicService extends Service {

    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "music_channel";
    private static final String CHANNEL_NAME = "音乐播放控制";
    private String title;
    private String artist;
    private String duration;
    // 远程视图，用于自定义通知布局
    private RemoteViews remoteViews;
    private MediaPlayer mMediaPlayer;
    private Cursor mCursor;
    private ContentResolver mContentResolver;
    private OnMusicPlayStateChangeListener mOnMusicPlayStateChangeListener;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("asdf", "=====onCreate=====");
        initPlayer();
        mContentResolver = getContentResolver();
        initPlaylist();
        // 初始化远程视图
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_custom);
        // 创建通知渠道
        createNotificationChannel();

        // 设置通知点击事件和按钮事件
        setupNotificationActions();

        // 更新通知显示
        updateNotification();

        // 启动前台服务
        startForeground(NOTIFICATION_ID, buildNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("asdf", "=====onStartCommand=====");
        if (intent != null && intent.getAction() != null) {
            // 处理从广播接收器传来的动作
            switch (intent.getAction()) {
                case NotificationReceiver.ACTION_PREV:
                    last();
                    break;
                case NotificationReceiver.ACTION_PLAY_PAUSE:
                    if (isPlaying()) {
                        pause();
                    } else {
                        play();
                    }
                    break;
                case NotificationReceiver.ACTION_NEXT:
                    next();
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("asdf", "=====onBind=====");
        return new MyBinder();
    }

    @Override
    public void onDestroy() {
        Log.d("asdf", "=====onDestroy=====");
        super.onDestroy();
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    public final class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    private void initPlayer() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("asdf", "播放结束!");
                next();
            }
        });
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {//解决开始播放就提示播放结束
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
    }

    private void initPlaylist() {//查询媒体数据，初始化播放列表
        // 查询媒体库
        Uri contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        //在这里的projection中添加上专辑和音乐地址的查询，这样下面的itemClickListener才能获得媒体地址，mMediaPlayer才能启动
        String[] projection = new String[]{
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.DATA};
        String selection = MediaStore.Audio.Media.DATA + " LIKE ? ";
        String[] selectionArgs = {"%/Music/QQMusic/%"};
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

        if (mContentResolver != null) {
            mCursor = mContentResolver.query(
                    contentUri, projection, selection, selectionArgs, sortOrder);
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onMusicListChanged(mCursor);
            }
        }
    }

    public void getDataByCursor(int position) {
        if (mCursor != null && mCursor.moveToPosition(position)) {
            getDataByCursor(mCursor);
        }
    }

    private void getDataByCursor(Cursor cursor) {
        int titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        //媒体地址
        int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        if (titleIndex >= 0 && artistIndex >= 0) {
            title = cursor.getString(titleIndex);
            artist = cursor.getString(artistIndex);
            String data = cursor.getString(dataIndex);
            Uri dataUri = Uri.parse(data);
            if (mMediaPlayer != null) {
                try {
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(getApplicationContext(), dataUri);
                    mMediaPlayer.prepare();
                    mMediaPlayer.start();
                    if (mOnMusicPlayStateChangeListener != null) {
                        mOnMusicPlayStateChangeListener.onPlayStart();
                        new Thread(new MusicProgressRunnable()).start();
                    }
                    updateNotification();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onMusicInfoChanged(title, artist);
            }
        }
    }


    public void setOnMusicPlayStateChangeListener(OnMusicPlayStateChangeListener l) {
        mOnMusicPlayStateChangeListener = l;
    }

    public Cursor getCursor() {
        return mCursor;
    }

    public void play() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onPlayStart();
            }
            updateNotification();
        }
    }

    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onPlayStop();
            }
            updateNotification();
        }
    }

    public void last() {
        Log.d("asdf", "=======last=======");
        if (mCursor != null) {
            if (mCursor.moveToPrevious()) {//游标向前移动，如不成功走到 else if

            } else if (mCursor.moveToLast()) { //游标移动到最后一条数据

            }
            getDataByCursor(mCursor);
        }
    }

    public void next() {
        Log.d("asdf", "=======next=======");
        if (mCursor != null) {
            if (mCursor.moveToNext()) {//游标向后移动，如不成功走到 else if

            } else if (mCursor.moveToFirst()) { //游标移动到第一条数据

            }
            getDataByCursor(mCursor);
        }
    }

    public int getDuration() {//获取音乐时长
        int duration = 0;
        if (mMediaPlayer != null) {
            duration = mMediaPlayer.getDuration();
        }
        return duration;
    }

    public int getCurrentPosition() {//当前播放时长
        int position = 0;
        if (mMediaPlayer != null) {
            position = mMediaPlayer.getCurrentPosition();
        }
        return position;
    }

    public boolean isPlaying() {//是否正在播放
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public void seekTo(int progress) {//改变进度
        if (mMediaPlayer != null) {
            Log.d("asdf", "seekTo ==" + progress);
            mMediaPlayer.seekTo(progress);
        }
    }

    // 创建通知渠道（Android 8.0+ 必需）
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_LOW
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }

    // 设置通知的点击事件和按钮事件
    private void setupNotificationActions() {
        // 设置通知整体点击事件（打开主界面）
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                0,
                intent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.iv_album, pendingIntent);

        // 设置上一首按钮事件
        Intent prevIntent = new Intent(this, NotificationReceiver.class);
        prevIntent.setAction(NotificationReceiver.ACTION_PREV);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(
                this,
                1,
                prevIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_prev, prevPendingIntent);

        // 设置播放/暂停按钮事件
        Intent playPauseIntent = new Intent(this, NotificationReceiver.class);
        playPauseIntent.setAction(NotificationReceiver.ACTION_PLAY_PAUSE);
        PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(
                this,
                2,
                playPauseIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_play_pause, playPausePendingIntent);

        // 设置下一首按钮事件
        Intent nextIntent = new Intent(this, NotificationReceiver.class);
        nextIntent.setAction(NotificationReceiver.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(
                this,
                3,
                nextIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_next, nextPendingIntent);
    }

    // 构建通知
    private Notification buildNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

        // 设置通知的基本属性
        builder.setSmallIcon(R.mipmap.music)
                .setCustomContentView(remoteViews)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true) // 通知常驻，用户不能手动滑动删除
                .setOnlyAlertOnce(true); // 只在第一次显示时提醒

        return builder.build();
    }

    // 更新通知显示内容
    private void updateNotification() {
        // 更新歌曲信息
        remoteViews.setTextViewText(R.id.tv_title, title);
        remoteViews.setTextViewText(R.id.tv_artist, artist);
        remoteViews.setTextViewText(R.id.tv_duration, duration);

        // 更新播放/暂停按钮图标
        if (isPlaying()) {
            remoteViews.setImageViewResource(R.id.btn_play_pause, R.mipmap.pause);
        } else {
            remoteViews.setImageViewResource(R.id.btn_play_pause, R.mipmap.play);
        }

        // 刷新通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.notify(NOTIFICATION_ID, buildNotification());//需要添加权限
        }
    }

    private class MusicProgressRunnable implements Runnable {
        public MusicProgressRunnable() {
        }

        @Override
        public void run() {
            boolean mThreadWorking = true;
            while (mThreadWorking) {
                try {
                    int time = getDuration() - getCurrentPosition();
                    duration = Utils.formatMsToMMSS(time);
                    updateNotification();
                    mThreadWorking = isPlaying();
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}